<template>
  <view class="h-100 tui-flex tui-flex-column px-5 container">
    <view class="tui-flex-1 tui-flex tui-flex-column p-5">
      <view class="tui-flex-1 border p-5">
        <textarea
          class="h-100 source-text"
          maxlength="-1"
          placeholder="请输入解析源规则（json）"
          v-model="source"
          :disabled="removeConfirm"
        />
      </view>
    </view>
    <view class="tui-flex tui-flex-column p-5">
      <tui-button @click="format">格式化</tui-button>
      <view class="tui-flex w-100">
        <tui-button
          class="tui-flex-1 px-5"
          v-if="_id"
          type="danger"
          shape="circle"
          @click="deleteSource"
        >删除</tui-button>
        <tui-button class="tui-flex-1 px-5" type="primary" shape="circle" @click="submit">提交</tui-button>
      </view>
    </view>
    <tui-modal
      :show="removeConfirm"
      @click="handleRemove"
      @cancel="hideConfirm"
      content="确定删除该解析源吗？可以修改enable=false禁用该解析源！"
      color="#333"
      :size="32"
      :button="confirmButtons"
    ></tui-modal>
  </view>
</template>

<script>
import tuiButton from "@/components/button/button.vue";
import tuiModal from "@/components/modal/modal";
import { formatJson, parseJson, isNullOrEmpty } from "@/utils/util.js";

export default {
  components: { tuiButton, tuiModal },
  data() {
    return {
      source: "",
      _id: "",
      textWidth: 300,
      removeConfirm: false,
      confirmButtons: [
        { text: "取消", type: "gray" },
        { text: "确定", type: "danger" }
      ]
    };
  },
  onLoad() {
    uni.getSystemInfo({
      success: res => {
        console.log(res);
        this.textWidth = res.windowWidth - uni.upx2px(32);
      }
    });
    uni.getStorage({
      key: "source_edit",
      success: res => {
        // 编辑源
        this._id = res.data._id;
        delete res.data._id;
        delete res.data._openid;
        this.source = formatJson(res.data);
      },
      fail: err => {
        // 添加源
      }
    });
  },
  onUnload() {
    uni.removeStorage({
      key: "source_edit"
    });
  },
  methods: {
    deleteSource() {
      if (!this._id) {
        this.tui.toast("缺失主键_id!");
        return;
      }
      this.removeConfirm = true;
    },
    hideConfirm() {
      this.removeConfirm = false;
    },
    handleRemove({ index }) {
      if (index == 0) {
        this.removeConfirm = false;
      } else if (index == 1) {
        uni.showLoading({
          title: "加载中"
        });
        this.db
          .collection("book_sources")
          .doc(this._id)
          .remove()
          .then(res => {
            uni.hideLoading();
            if (res.errMsg == "document.remove:ok") {
              if (res.stats.removed == 1) {
                this.tui.toast("删除成功", null, true);
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1
                  });
                }, 1000);
              } else {
                console.log("res", res);
                this.tui.toast("删除失败");
              }
            } else {
              this.tui.toast(res.errMsg);
            }
          })
          .catch(e => {
            uni.hideLoading();
            console.error(e);
            this.tui.toast(e.errMsg);
          });
      }
    },
    format() {
      const source = this.judgeSource();
      if (source === null || typeof source !== "object") {
        this.tui.toast("数据有错误，无法格式化");
        return;
      }
      this.source = formatJson(source);
      this.tui.toast("格式化成功", null, true);
    },
    submit() {
      const source = this.judgeSource();
      if (source === null || typeof source !== "object") {
        this.tui.toast("数据有错误，无法提交");
        return;
      }
      if (isNullOrEmpty(this._id)) {
        // 添加解析源
        uni.showLoading({
          title: "加载中"
        });
        this.db
          .collection("book_sources")
          .add({
            data: source
          })
          .then(res => {
            // console.log("res:", res);
            uni.hideLoading();
            if (res.errMsg === "collection.add:ok") {
              this._id = res._id;
              this.tui.toast("添加成功", null, true);
              const pages = getCurrentPages();
              pages.some(page => {
                if (page.route == "pages/admin/sources") {
                  page.onLoad({ refresh: true });
                  return true;
                }
              });
            } else {
              this.tui.toast(res.errMsg);
            }
          })
          .catch(e => {
            uni.hideLoading();
            console.error(e);
            this.tui.toast(e.errMsg);
          });
      } else {
        // 修改解析源
        uni.showLoading({
          title: "加载中"
        });
        this.db
          .collection("book_sources")
          .doc(this._id)
          .update({
            data: source
          })
          .then(res => {
            // console.log("res:", res);
            uni.hideLoading();
            if (res.errMsg == "document.update:ok") {
              if (res.stats.updated == 1) {
                this.tui.toast("修改成功", null, true);
                const pages = getCurrentPages();
                pages.some(page => {
                  if (page.route == "pages/admin/sources") {
                    page.onLoad({ refresh: true });
                    return true;
                  }
                });
              } else {
                this.tui.toast("没有任何修改");
              }
            } else {
              this.tui.toast(res.errMsg);
            }
          })
          .catch(e => {
            uni.hideLoading();
            console.error(e);
            this.tui.toast(e.errMsg);
          });
      }
    },
    judgeSource() {
      let source = null;
      if (isNullOrEmpty(this.source.trim())) {
        this.tui.toast("解析源规则为空，请输入");
        return source;
      }
      try {
        const json = parseJson(this.source);
        source = JSON.parse(json);
      } catch (error) {
        console.error(error);
      }
      return source;
    }
  }
};
</script>

<style>
.container {
  overflow: hidden;
}
page {
  height: 100%;
}
.px-5 {
  padding-left: 5upx;
  padding-right: 5upx;
}
.p-5 {
  padding: 5upx;
}
.border {
  border: 1upx #9b9b9b solid;
  border-radius: 5upx;
}
.source-text {
  word-break: break-all;
  word-wrap: normal;
  white-space: nowrap;
  overflow-x: auto;
  width: auto;
}
</style>